package com.hsd.survey.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.hsd.commons.model.HsdAccount;
import com.hsd.commons.util.DateUtil;
import com.hsd.survey.SurveyConstants;
import com.hsd.survey.model.HsdModelAnswer;
import com.hsd.survey.model.HsdModelPage;
import com.hsd.survey.model.HsdModelQuestion;
import com.hsd.survey.model.HsdModelSurvey;
import com.hsd.survey.util.SurveyUtil;

/**
 * <p>
 * 类描述：问卷系统工具类
 * <p>
 * 创建人：Abdi
 * <p>
 * 创建时间：Oct 2, 2013 5:34:08 PM
 */
public class SurveyModelHelper {
	/******************************************输出********************************************************/
	/**
	 * 将数据库内容转展示内容
	 * @param survey
	 * @return
	 */
	public static JSONObject toDisplaySurvey(HsdModelSurvey survey){
		JSONObject result = new JSONObject();
		result.put("id", survey.getSurveyuuid());
		result.put("name", survey.getName());
		result.put("subname", survey.getSubname());
		result.put("description", survey.getDescription());
		result.put("descriptiontext", survey.getDescriptiontext());
		result.put("createtype", survey.getCreatetype());
		result.put("type", survey.getType());
		result.put("logo", survey.getLogo());
		result.put("progressbar", survey.getProgressbar());
		result.put("pagecount", survey.getPagecount());
		result.put("questioncount", survey.getQuestioncount());
		result.put("timeschedule", survey.getTimeschedule());
		result.put("starttime", survey.getStarttime());
		result.put("endtime", survey.getEndtime());
		result.put("createtime", survey.getCreatetime());
		result.put("firstsavetime", survey.getFirstsavetime());
		result.put("isopen", survey.getIsopen());
		result.put("modifytime", survey.getModifytime());
		result.put("logicdel", survey.getLogicdel());
		result.put("logicdeltime", survey.getLogicdeltime());
		return result;
	}
	
	/**
	 * 问题转展示
	 * @param list
	 * @return
	 */
	public static JSONArray toDisplayQuestion(JSONArray questionlist){
		for(Object questionObj : questionlist){
			// 问题
			JSONObject question = (JSONObject)questionObj;
			question.put("fatherquestionid", question.get("fatherquestionuuid"));
			question.remove("fatherquestionuuid");
			question.put("id", question.get("questionuuid"));
			question.remove("questionuuid");
			question.put("pageid", question.get("pageuuid"));
			question.remove("pageuuid");
			question.put("surveyid", question.get("surveyuuid"));
			question.remove("surveyuuid");
			
			// 答案
			JSONArray answers = question.getJSONArray("answers");
			for(Object answerObj : answers){
				JSONObject answer = (JSONObject)answerObj;
				answer.put("id", answer.get("answeruuid"));
				answer.remove("answeruuid");
				answer.put("questionid", answer.get("questionuuid"));
				answer.remove("questionuuid");
				answer.put("surveyid", answer.get("surveyuuid"));
				answer.remove("surveyuuid");
			}
			
			// 子问题
			JSONArray childQuestions = question.getJSONArray("questions");
			for(Object childObj : childQuestions){
				JSONObject childQuestion = (JSONObject)childObj;
				// 子问题问题
				childQuestion.put("fatherquestionid", childQuestion.get("fatherquestionuuid"));
				childQuestion.remove("fatherquestionuuid");
				childQuestion.put("id", childQuestion.get("questionuuid"));
				childQuestion.remove("questionuuid");
				childQuestion.put("pageid", childQuestion.get("pageuuid"));
				childQuestion.remove("pageuuid");
				childQuestion.put("surveyid", childQuestion.get("surveyuuid"));
				childQuestion.remove("surveyuuid");
				
				// 子问题答案
				JSONArray childAnswers = childQuestion.getJSONArray("answers");
				for(Object childAnswerObj : childAnswers){
					JSONObject childAnswer = (JSONObject)childAnswerObj;
					childAnswer.put("id", childAnswer.get("answeruuid"));
					childAnswer.remove("answeruuid");
					childAnswer.put("questionid", childAnswer.get("questionuuid"));
					childAnswer.remove("questionuuid");
					childAnswer.put("surveyid", childAnswer.get("surveyuuid"));
					childAnswer.remove("surveyuuid");
				}
			}
		}
		System.out.println("====>>>> questionlist " + questionlist);
		return questionlist;
	} 
	
	/**
	 * 分页转展示
	 * @return
	 */
	public static JSONArray toDisplayPage(List<HsdModelPage> pagelist){
		JSONArray result = new JSONArray();
		for(HsdModelPage page : pagelist){
			JSONObject json = new JSONObject();
			json.put("createtime", page.getCreatetime());
			json.put("id", page.getPageuuid());
			json.put("modifytime", page.getModifytime());
			json.put("sortindex", page.getSortindex());
			json.put("surveyid", page.getSurveyuuid());
			json.put("type", page.getType());
			result.add(json);
		}
		return result;
	}
	
	
	/******************************************输入********************************************************/
	/**
	 * 初始化问卷信息
	 * @return
	 */
	public static HsdModelSurvey initModelSurvey(String name,String createType,String type,String isopen,HsdAccount accInfo){
		HsdModelSurvey modelSurvey = new HsdModelSurvey();
		modelSurvey.setSurveyuuid(UUID.randomUUID().toString());
		modelSurvey.setName(name);
		modelSurvey.setDescription("这是我的问卷，希望得到您的回复！");
		modelSurvey.setDescriptiontext("这是我的问卷，希望得到您的回复！");
		modelSurvey.setTimeschedule(0);
		modelSurvey.setCreatetype(Integer.parseInt(null == createType ? "1" : createType));
		modelSurvey.setType(Integer.parseInt(null == type ? "1" : type));
		modelSurvey.setProgressbar(0);
		modelSurvey.setCreatetime(DateUtil.currentDateTime());
		modelSurvey.setFirstsavetime(DateUtil.currentDateTime());
		modelSurvey.setIsopen(Integer.parseInt(null == isopen ? "1" : isopen));
		if(null != accInfo){
			modelSurvey.setCreatoraccount(accInfo.getId());
			modelSurvey.setCreatorname(accInfo.getUsername());
		}
		modelSurvey.setStatus(Integer.parseInt(SurveyConstants.DESIGN_PUBLISH_WAIT));
		return modelSurvey;
	}
	
	/**
	 * 刷新问卷信息
	 * @return
	 */
	public static void refreshModelSurvey(HsdModelSurvey survey,JSONObject surveyJson){
		survey.setName(surveyJson.getString("name"));
		if(null != surveyJson.get("description")){
			survey.setDescription(surveyJson.getString("description"));
		}
		if(null != surveyJson.get("descriptiontext")){
			survey.setDescriptiontext(surveyJson.getString("descriptiontext"));
		}
		survey.setIsopen(surveyJson.getInt("isopen"));
	}
	
	/**
	 * 刷新页面信息
	 * @param jsonArray
	 * @return
	 */
	public static Map<String,HsdModelPage> refreshPageInfo(String pagelist,String surveyuuid){
		Map<String,HsdModelPage> map = new HashMap<String, HsdModelPage>();
		if(isEmptyJSON(pagelist)){
			return map;
		}
		JSONArray jsonArray = JSONArray.fromObject(pagelist);
		for(Object obj : jsonArray){
			if(!isEmptyJSON(obj.toString())){
				JSONObject pageJson = JSONObject.fromObject(obj);
				HsdModelPage modelPage = new HsdModelPage();
				modelPage.setSurveyuuid(surveyuuid);
				if(SurveyUtil.isUUIDFormat(pageJson.getString("id"))){
					modelPage.setPageuuid(pageJson.getString("id"));
				}else {
					modelPage.setPageuuid(UUID.randomUUID().toString());
				}
				modelPage.setSortindex(pageJson.getInt("index"));
				modelPage.setCreatetime(DateUtil.currentDateTime());
				map.put(pageJson.getString("id"), modelPage);
			}
		}
		return map;
	}
	
	/**
	 * 刷新问卷问题信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,List> refreshQuestionInfo(String questionlist,String surveyuuid,Map<String,HsdModelPage> pageMap){
		List<HsdModelAnswer> modelAnswerList = new ArrayList<HsdModelAnswer>();
		Map<String,List> refreshMap = getQuestionList(questionlist, surveyuuid, pageMap);
		refreshMap.put("deleteQuestion", modelAnswerList);
		return refreshMap;
	}
	
	/**
	 * 获取问题信息
	 * @param questionlist
	 * @param surveyuuid
	 * @param pageMap
	 */
	private static Map<String,List> getQuestionList(String questionlist,String surveyuuid,Map<String,HsdModelPage> pageMap){
		Map<String,List> map = new HashMap<String, List>();
		if(isEmptyJSON(questionlist)){
			return map;
		}
		List<HsdModelQuestion> questionList = new ArrayList<HsdModelQuestion>();
		List<HsdModelAnswer> answerList = new ArrayList<HsdModelAnswer>();
		JSONArray jsonArray = JSONArray.fromObject(questionlist);
		
		for(int i = 0 ; i < jsonArray.size() ; i++){
			Object obj = jsonArray.get(i);
			if(!isEmptyJSON(obj.toString())){
				JSONObject questionJson = JSONObject.fromObject(obj);
				HsdModelQuestion modelQuestion = new HsdModelQuestion();
				if(SurveyUtil.isUUIDFormat(questionJson.getString("id"))){
					modelQuestion.setQuestionuuid(questionJson.getString("id"));
				}else {
					modelQuestion.setQuestionuuid(UUID.randomUUID().toString());
				}
				modelQuestion.setSurveyuuid(surveyuuid);
				modelQuestion.setPageuuid(pageMap.get(questionJson.getString("pageid")).getPageuuid());
				modelQuestion.setSortindex(i + 1);
				modelQuestion.setType(questionJson.getInt("type"));
				modelQuestion.setTypeid(questionJson.getInt("typeid"));
				modelQuestion.setDescription(questionJson.getString("description"));
				modelQuestion.setDescriptionview(questionJson.getString("descriptionview"));
				modelQuestion.setIsgridchildquestion(questionJson.getInt("isgridchildquestion"));
				//modelQuestion.setFatherquestionuuid(questionJson.getString("fatherquestionuuid"));
				modelQuestion.setFormat(null == questionJson.get("format") ? null : questionJson.getInt("format"));
				modelQuestion.setRequired(questionJson.getInt("required"));
				modelQuestion.setImageurl(questionJson.getString("imageurl"));
				modelQuestion.setInstruction(questionJson.getString("instruction"));
				modelQuestion.setImagetype(null == questionJson.get("imagetype") ? null : questionJson.getInt("imagetype"));
				modelQuestion.setImagewidth(null == questionJson.get("imagewidth") ? null : questionJson.getInt("imagewidth"));
				modelQuestion.setImageheight(null == questionJson.get("imageheight") ? null : questionJson.getInt("imageheight"));
				modelQuestion.setShowpoint(questionJson.getInt("showpoint"));
				modelQuestion.setShowhasother(questionJson.getInt("showhasother"));
				modelQuestion.setRangeformat(questionJson.getInt("rangeformat"));
				modelQuestion.setRangeformat(questionJson.getInt("rangemax"));
				modelQuestion.setRangeformat(questionJson.getInt("rangemin"));
				modelQuestion.setCreatetime(DateUtil.currentDateTime());
				// 子问题存储
				String questions = questionJson.getString("questions");
				System.out.println("=======>>>>> 111111111  " + questions);
				if(!isEmptyJSON(questions)){
					addChildrenQuestions(questionList,answerList,modelQuestion,questions,surveyuuid,pageMap);
				}
				questionList.add(modelQuestion);
				getAnswerList(answerList, questionJson.getString("answers"),modelQuestion);
			}
		}
		map.put("saveQuestion", questionList);
		map.put("saveAnswer", answerList);
		return map;
	}
	
	/**
	 * 添加子问题
	 * @param questionlist
	 */
	private static void addChildrenQuestions(List<HsdModelQuestion> questionList,List<HsdModelAnswer> answerList,
			HsdModelQuestion resultQuestion,String questionlist,String surveyuuid,Map<String,HsdModelPage> pageMap){
		JSONArray jsonArray = JSONArray.fromObject(questionlist);
		
		for(int i = 0 ; i < jsonArray.size() ; i++){
			Object obj = jsonArray.get(i);
			if(!isEmptyJSON(obj.toString())){
				JSONObject questionJson = JSONObject.fromObject(obj);
				HsdModelQuestion modelQuestion = new HsdModelQuestion();
				if(SurveyUtil.isUUIDFormat(questionJson.getString("id"))){
					modelQuestion.setQuestionuuid(questionJson.getString("id"));
				}else {
					modelQuestion.setQuestionuuid(UUID.randomUUID().toString());
				}
				modelQuestion.setSurveyuuid(surveyuuid);
				//modelQuestion.setPageuuid(pageMap.get(questionJson.getString("pageid")).getPageuuid());
				modelQuestion.setSortindex(i + 1);
				modelQuestion.setType(questionJson.getInt("type"));
				modelQuestion.setTypeid(questionJson.getInt("typeid"));
				modelQuestion.setDescription(questionJson.getString("description"));
				modelQuestion.setDescriptionview(questionJson.getString("descriptionview"));
				modelQuestion.setIsgridchildquestion(questionJson.getInt("isgridchildquestion"));
				modelQuestion.setFatherquestionuuid(resultQuestion.getQuestionuuid());
				modelQuestion.setFormat(null == questionJson.get("format") ? null : questionJson.getInt("format"));
				modelQuestion.setRequired(questionJson.getInt("required"));
				modelQuestion.setImageurl(questionJson.getString("imageurl"));
				modelQuestion.setInstruction(questionJson.getString("instruction"));
				modelQuestion.setImagetype(null == questionJson.get("imagetype") ? null : questionJson.getInt("imagetype"));
				modelQuestion.setImagewidth(null == questionJson.get("imagewidth") ? null : questionJson.getInt("imagewidth"));
				modelQuestion.setImageheight(null == questionJson.get("imageheight") ? null : questionJson.getInt("imageheight"));
				modelQuestion.setShowpoint(questionJson.getInt("showpoint"));
				modelQuestion.setShowhasother(questionJson.getInt("showhasother"));
				modelQuestion.setRangeformat(questionJson.getInt("rangeformat"));
				modelQuestion.setRangeformat(questionJson.getInt("rangemax"));
				modelQuestion.setRangeformat(questionJson.getInt("rangemin"));
				modelQuestion.setCreatetime(DateUtil.currentDateTime());
				questionList.add(modelQuestion);
				//getAnswerList(answerList, questionJson.getString("answers"),modelQuestion);
			}
		}
	}
	
	/**
	 * 获取答案信息
	 * @param answerlist
	 * @param modelQuestion
	 */
	private static void getAnswerList(List answerList,String answerlist,HsdModelQuestion modelQuestion){
		System.out.println(answerlist);
		if(isEmptyJSON(answerlist)){
			return;
		}
		JSONArray jsonArray = JSONArray.fromObject(answerlist);
		for(int i = 0 ; i < jsonArray.size() ; i++){
			Object obj = jsonArray.get(i);
			if(!isEmptyJSON(obj.toString())){
				JSONObject answerJson = JSONObject.fromObject(obj);
				HsdModelAnswer modelAnswer = new HsdModelAnswer();
				if(SurveyUtil.isUUIDFormat(answerJson.getString("id"))){
					modelAnswer.setAnsweruuid(answerJson.getString("id"));
				}else {
					modelAnswer.setAnsweruuid(UUID.randomUUID().toString());
				}
				modelAnswer.setSurveyuuid(modelQuestion.getSurveyuuid());
				modelAnswer.setQuestionuuid(modelQuestion.getQuestionuuid());
				modelAnswer.setSortindex(i + 1);
				modelAnswer.setName(answerJson.getString("name"));
				modelAnswer.setHasother(answerJson.getInt("hasother"));
				modelAnswer.setPoint(answerJson.getInt("point"));
				modelAnswer.setImagetype(answerJson.getInt("imagetype"));
				modelAnswer.setImageurl(answerJson.getString("imageurl"));
				modelAnswer.setImageheight(answerJson.getInt("imageheight"));
				modelAnswer.setImagewidth(answerJson.getInt("imagewidth"));
				answerList.add(modelAnswer);
			}
		}
	}
	
	/**
	 * 判断JSON数据是否为空
	 * @param json
	 * @return
	 */
	private static boolean isEmptyJSON(String json){
		return "{}".equals(json) || "[]".equals(json);
	}
	
	public static void main(String[] args) {
		String pageList = "[{\"id\":\"1381120560159\",\"index\":0},{\"id\":\"1381120545552\",\"index\":1}]";
	}
}